package com.ai.core.context;

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.MethodInvoker;

import com.ai.core.exception.CoreException;

@Component
public class SpringContextUtil implements ApplicationContextAware {
	static Log logger = LogFactory.getLog(SpringContextUtil.class);
	private static ApplicationContext applicationContext;

	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextUtil.applicationContext = applicationContext;
	}

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) throws BeansException {
		return (T) applicationContext.getBean(name);
	}

	/**
	 * 获取Bean对象
	 * 
	 * @param name
	 *            bean的配置名称
	 * @param requiredType
	 *            bean的类型
	 * @return bean对象
	 */
	public static <T> T getBean(String name, Class<T> requiredType) {
		return applicationContext.getBean(name, requiredType);
	}

	/**
	 * 获取Bean对象
	 * 
	 * @param requiredType
	 *            bean的类型
	 * @return bean对象
	 */
	public static <T> T getBean(Class<T> requiredType) {
		return applicationContext.getBean(requiredType);
	}

	/**
	 * 运行Bean中指定名称的方法并返回其返回值
	 * 
	 * @param object
	 *            object对象
	 * @param methodName
	 *            方法名
	 * @param arguments
	 *            参数值
	 * @return 运行bean中指定名称的方法的返回值
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 * @throws ClassNotFoundException
	 */
	public static Object invokeBeanMethod(String beanName, String methodName, Object[] arguments) {
		try {
			// 初始化
			MethodInvoker methodInvoker = new MethodInvoker();
			methodInvoker.setTargetObject(SpringContextUtil.getBean(beanName));
			methodInvoker.setTargetMethod(methodName);

			// 设置参数
			if (arguments != null && arguments.length > 0) {
				methodInvoker.setArguments(arguments);
			}

			// 准备方法
			methodInvoker.prepare();

			// 执行方法
			return methodInvoker.invoke();
		} catch (ClassNotFoundException e) {
			throw new CoreException(e);
		} catch (NoSuchMethodException e) {
			throw new CoreException(e);
		} catch (InvocationTargetException e) {
			throw new CoreException(e);
		} catch (IllegalAccessException e) {
			throw new CoreException(e);
		}
	}
}